<?php

/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Game
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
class Game_BridgeController extends Core_Controller_Action_Standard
{
  
  protected $_log;
  
  public function initLog()
  {
    if ($this->_log === null)
    {
      $this->_log = new Zend_Log();
      $this->_log->addWriter(new Zend_Log_Writer_Stream(APPLICATION_PATH . '/temporary/log/game_bridge.log'));
    }
  }
  
  /**
    const EMERG   = 0;  // Emergency: system is unusable
    const ALERT   = 1;  // Alert: action must be taken immediately
    const CRIT    = 2;  // Critical: critical conditions
    const ERR     = 3;  // Error: error conditions
    const WARN    = 4;  // Warning: warning conditions
    const NOTICE  = 5;  // Notice: normal but significant condition
    const INFO    = 6;  // Informational: informational messages
    const DEBUG   = 7;  // Debug: debug messages
   */
  protected function log($message, $priority = Zend_Log::INFO)
  {
    $this->initLog();
    $this->_log->log($message, $priority);
  }
  
  public function scoreAction()
  {
    if (!$this->getRequest()->isPost()) {
      $this->log("Incorrect SCORE request method, only POST allow.", Zend_Log::WARN);
      exit;
    }
    
    $params = $this->getRequest()->getPost();
    ksort($params);
    
    $this->log("Received Score Data: " . print_r($params, true), Zend_Log::DEBUG);
    
    if (empty($params['signature'])) {
      $this->log("Missing signature key", Zend_Log::ERR);
      exit;
    }
    
    if (empty($params['signature'])) {
      $this->log("Missing submission key", Zend_Log::ERR);
      exit;
    }    
        
    $user = Engine_Api::_()->getItem('user', $params['userID']);
    if (!$user) {
      $this->log("Could not find user ID = ".$params['userID'], Zend_Log::ERR);
      exit;
    }

    $validateData = $this->_validateBridgeData($params);
    $debugMode = Engine_Api::_()->getApi('settings', 'core')->getSetting('game.mochibridgedebug');
    
    if ($debugMode) {
      $this->log("Debug Mode activated, signature validate result = ".($validateData ? 'PASS' : 'FAIL'), Zend_Log::INFO);
    }
    elseif (!$validateData) {
      $this->log("Invalid signature key", Zend_Log::ERR);
      exit;
    }
    
    $game = Engine_Api::_()->getItem('game', $params['sessionID']);
    if (!$game) {
      $this->log("Could not find game ID = ".$params['sessionID'], Zend_Log::ERR);
      exit;
    }
    if ($game->distributor_ref_id != $params['gameID']) {
      $this->log("Game ID ".$params['sessionID']." tag $game->distributor_ref_id not match ".$params['gameID'], Zend_Log::ERR);
      exit;
    }    
    
    $submission = $params['submission'];
    
    if ($submission == 'score')
    {
      $values = array(
        'game_id' => $game->getIdentity(),
        'user_id' => $user->getIdentity(),
        'score' => $params['score'],
        'score_label' => $params['scoreLabel'],
        'sort_order' => $params['sortOrder'],
        'datatype' => $params['datatype'],
        'board_id' => $params['boardID'],
        'game_tag' => $params['gameID'],
      );
      

      $db = Engine_Api::_()->getItemTable('game_score')->getAdapter();
      $db->beginTransaction();
      
      try
      {
        $table = Engine_Api::_()->getItemTable('game_score');
        $score = $table->createRow();
        $score->setFromArray($values);
        $score->save();    
  
        //$score->refresh();
        
        
        
        // Add activity
        $activityApi = Engine_Api::_()->getDbtable('actions', 'activity');
        $action = $activityApi->addActivity($user, $game, 'game_score', null, array(
          'score' => $score->score,
        ));
        
        if( $action ) {
          $activityApi->attachActivity($action, $game);
        }
        
        $db->commit();
        $this->log("Saved score ID = ".$score->getIdentity(), Zend_Log::INFO);
      }
      catch( Exception $e )
      {
        $db->rollBack();
        
        $this->log("Exception = ".$e->__toString(), Zend_Log::CRIT);
      }
      //
    }
    
    exit;
  }

  
  public function autopostAction()
  {
    $autopost = Engine_Api::_()->getApi('settings', 'core')->game_autopost;
    
    if (empty($autopost)) {
      $this->log("Mochi Auto Post settings failed to load", Zend_Log::ERR);
      exit;
    }
    
    if (!$autopost['enabled']) {
      $this->log("Mochi Auto Post is disabled.", Zend_Log::NOTICE);
      exit;
    }
    
    if (!$this->getRequest()->isPost()) {
      $this->log("Incorrect AUTOPOST request method, only POST allow.", Zend_Log::WARN);
      exit;
    }
    
    $params = $this->getRequest()->getPost();
    
    $this->log("Received AUTOPOST Data: " . print_r($params, true), Zend_Log::DEBUG);
    
    if (!isset($params['game_tag'])) {
      $this->log("Missing game_tag parameter", Zend_Log::ERR);
      exit;
    }
    
    $game_tag = $params['game_tag'];
    
    $params = array('distributor_type' => 'mochi', 'distributor_ref_id' => $game_tag);
    $existing = Engine_Api::_()->getItemTable('game')->countGames($params);
    
    if ($existing) {
      $this->log("Found existing game with game_tag=".$game_tag, Zend_Log::NOTICE);
      exit;
    }
    
    $publisher_id = Engine_Api::_()->getApi('settings', 'core')->getSetting('game.mochipublisherid');
    
    if (!$publisher_id) {
      $this->log("Mochi Publisher ID is required. Need to update this value in Admin :: Games :: Global Settings", Zend_Log::ERR);
      exit;
    }
    
    $viewer = Engine_Api::_()->game()->getDefaultOwner();
    if (!$viewer->getIdentity()) {
      $this->log("Could NOT find default game owner", Zend_Log::ERR);
      exit;
    }
    
    
    $feedUrl = "http://www.mochimedia.com/feeds/games/$publisher_id/$game_tag/?format=json";
    
    $distributor = Engine_Api::_()->getItemTable('game_distributor')->getDistributor('mochi');
    
    $values = array(
      'status' => $autopost['gamestatus'] ? $autopost['gamestatus'] : Game_Model_Game::STATUS_PENDING,
    );
    
    try 
    {
      $config = array_merge($distributor->config, $values);
      $plugin = $distributor->getPlugin();
      $plugin->loadConfig($config);
      
      $this->log("Try to fetch URL: ".$feedUrl, Zend_Log::INFO);
      
      $data = $plugin->fetchGames($feedUrl);
    }
    catch (Exception $e) {
      $this->log("Exception ".$e->__toString(), Zend_Log::CRIT);
      exit;
    }
    
    if (count($data))
    {

      $categoryMapping = Engine_Api::_()->getApi('settings', 'core')->game_categorymapping;

      foreach ($data as $k => $values)
      {
        $params = array('distributor_type' => $distributor->type, 'distributor_ref_id' => $values['distributor_ref_id']);
        $existing = Engine_Api::_()->getItemTable('game')->countGames($params);
        if (!$existing)
        {
          $values['distributor_type'] = $distributor->type;
          
          $values = Engine_Api::_()->game()->importGame($values, $autopost);  
          
          if (is_int($values['import_result']) && !empty($values['game_id']) && null !== ($game = Engine_Api::_()->getItem('game', $values['game_id'])))
          {
            // Add activity
            $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $game, 'game_new');
            if ($action != null)
            {
              Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $game);
            }
          }
        }
        else
        {
          $values['import_result'] = 'already exist';
        }
        
        $data[$k] = $values;
      }

      //$this->log("Imported Data = ".print_r($data, true), Zend_Log::INFO);
    }
    
    $this->log("Imported Auto Post Data=".print_r($data, true), Zend_Log::INFO);
    
    
    $this->view->games = $data;
  }
  
  protected function _validateBridgeData($data)
  {
    $ds = array();
    ksort($data);
    foreach ($data as $k => $v) {
      if ($k == "signature") continue;
      $ds[] = $k."=".rawurlencode($v);
    }
    
    $string = join("&", $ds) . Engine_Api::_()->getApi('settings', 'core')->getSetting('game.mochisecretkey');
    
    return md5($string) == $data['signature'];
  }
  
  
  public function profilePhotoAction()
  {
    $user = Engine_Api::_()->user()->getUser($this->_getParam('user_id'));
    
    $photoPath = null;
    if ($user->getIdentity())
    {
      $photoPath = $user->getPhotoUrl('thumb.icon');
    }
    
    if (!$photoPath)
    {
      $photoPath = $this->view->layout()->staticBaseUrl . 'application/modules/User/externals/images/nophoto_user_thumb_icon.png';
    }
    
    $url = (constant('_ENGINE_SSL') ? 'https://' : 'http://') 
      . Zend_Controller_Front::getInstance()->getRequest()->getHttpHost()
      . $photoPath;
    
    header("Location: $url");
    exit;
  }
  
  public function testAction()
  {
    /*
    $dd = array(
"boardID" => "80a48065ee5a26811890e0b8a3db6983",
"datatype" => "number",
"description" => "",
"gameID" => "61fed1a9a0bc474e",
"name" => "admin",
"score" => "0",
"scoreLabel" => "Score",
"sessionID" => "49",
"signature" => "8f78e6ae0ca6405ed717b4440a1a44a8",
"sortOrder" => "desc",
"submission" => "score",
"title" => "Highscores",
"userID" => "1",
"username" => "admin",        
        );
    
    $s = $this->_validateBridgeData($dd);
    var_dump($s);
    ///////
    die();
    */
    
    $data = array(
      "boardID" => "8b09910b56a46c7fe26cc0f3214e9552",
      "datatype" => "number",
      "description" => "",
      "gameID" => "9c8d73cdac6c27fc",
      "name" => "admin",
      "score" => rand(100, 99999),
      "scoreLabel" => "Score",
      "sessionID" => "515",
      "signature" => "ce637b2a98fd8f352abf87a6729e80d6",
      "sortOrder" => "desc",
      "submission" => "score",
      "title" => "Ninja Mushroom",
      "userID" => rand(1, 16),
      "username" => "admin",
      "signature" => time(),
    );
    
    $params = array(
      'limit' => $this->_getParam('max', 100),
      'leaderboard_enabled' => 1,
      'order' => 'random',
    );
    $games = Engine_Api::_()->game()->getGamesPaginator($params);
    
    foreach ($games as $game) {
      for ($c = 0; $c <= 10; $c++)
      {
        $data['title'] = $game->getTitle();
        $data['sessionID'] = $game->getIdentity();
        $data['gameID'] = $game->distributor_ref_id;
        $data['userID'] = rand(1, 10);
        $data['score'] = rand(100, 99999);
        if ($data['userID'] == 3) $data['userID'] = rand(4,16);
        
        $url = "http://127.0.0.1" . $this->_helper->url->url(array('controller' => 'bridge', 'action'=>'score'), 'game_extended', true);
        $client = new Zend_Http_Client($url);
        $client->setParameterPost($data);
        $response = $client->request('POST');
        echo $response;
      }
    }
    die('done');
  }
}

